前端analysis | What,Why,Who,When,Where,How

《Js》- js这些不得不了解的技巧,你使用过吗

2020-11-12

Console

copy

1
2
let x = {a:1,b:2,test:() =>{}}
copy(x) //copy 所有属性,方法不支持到文本编辑器ctrl+v

console.dir

查看所有对象的属性和方法

1
console.dir(x)

console.error

提供栈追踪

1
console.error()

console.timeEnd

code耗时

1
2
3
console.time()
//code
console.timeEnd()

console.log

所有obj 继承object toString

1
2
# 作为对象或字符串进行打印
console.log(x);

Array

of

1
2
3
4
5
6
7
8
9
# Array.of(element0[, element1[, ...[, elementN]]])

Array.of(undefined); // [undefined]
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]

Array(7); // [ , , , , , , ]
Array(1, 2, 3); // [1, 2, 3]

from

Array.from() lets you create Arrays from:

array-like objects (objects with a length property and indexed elements); or
iterable objects (objects such as Map and Set).

1
2
3
4
5
6
7
# Array.from(arrayLike [, mapFn [, thisArg]])

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

concat

不仅限于数组,还可以是任何值。
基本类型,copy value,修改不会对原数组产生影响;对象类型,copy reference,修改会对原对象产生影响。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# const new_array = old_array.concat([value1[, value2[, ...[, valueN]]]])

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
# 切记,需要赋值给数组哦,
const array3 = array1.concat(array2);

console.log(array1);
console.log(array2);
console.log(array3);

//output
["a", "b", "c"]
["d", "e", "f"]
["a", "b", "c", "d", "e", "f"]


const array1 = ['a', 'b', 'c'];
# 切记,需要赋值给数组哦,
const array3 = array1.concat(array1,2,3,{a:'b'});

console.log(array1);
console.log(array3);

//output
["a", "b", "c"]
["a", "b", "c", "a", "b", "c", 2, 3, {…}]

filter

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])

const words = ['spray', 'limit', 'elite', , 'destruction', 'present'];

const result = words.filter(
(word,index) => {
console.log(word,index);
return word.length > 6
}
);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

slice

切片,不影响原来数组

1
2
3
4
5
6
7
8
# arr.slice([start[, end]])

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals);


isArray

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array.isArray([1, 2, 3]);  // true
Array.isArray([]); // true
Array.isArray([1]); // true
Array.isArray(new Array()); // true
Array.isArray(new Array('a', 'b', 'c', 'd')); // true
Array.isArray(new Array(3)); // true

Array.isArray({foo: 123}); // false
Array.isArray("foobar"); // false
Array.isArray(undefined); // false
Array.isArray(null); // false
Array.isArray(new Uint8Array(32)); // false
Array.isArray({ __proto__: Array.prototype }); // false
Array.isArray(Array.prototype); // true

every

1
2
3
4
5
6
const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true
1
[12, 54, 18, 130, 44].every(x => x >= 10); // true

some

查找满足特定逻辑的元素,是否存在

1
2
3
4
5
6
7
8
9
10
# arr.some(callback(element[, index[, array]])[, thisArg])

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

修改元素,会立即生效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (item,index) => {
console.log("item value is ",item,index);
const res = item % 5 === 0;
const ix = index+1;
if(ix < array.length - 1){
array[ix] = array[ix] * 2;
console.log("array...",array);
}
return res;
}

console.log("result....",array.some(even),array);
// expected output: true , [1, 4, 6, 8, 5]


find

返回满足条件的第一个元素。 即使元素没有初始化,也会参与过滤

1
2
3
4
5
6
7
8
9
10
11
12
13
# arr.find(callback(element[, index[, array]])[, thisArg])
const array1 = [5 , , 130, 44];

const found = array1.find((element,ix) => { console.log(element,ix); return element > 10} );

console.log(found);


> 5 0
> undefined 1
> 130 2
> 130

findIndex

返回满足条件的第一个元素下标。 即使元素没有初始化,也会参与过滤,且不会影响原来的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# arr.findIndex(callback( element[, index[, array]] )[, thisArg])

const array1 = [5 , , 130, 44];

const found = array1.findIndex((element,ix) => { console.log(element,ix); return element > 10} );

console.log(array1);
console.log(found);

> 5 0
> undefined 1
> 130 2
> Array [5, undefined, 130, 44]
> 2

entries

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 # 解构
const a = ['a', 'b', 'c'];

for (const [index, element] of a.entries())
console.log(index, element);

// 0 'a'
// 1 'b'
// 2 'c'

var arr = ["a", "b", "c"];
var iter = arr.entries();
var a = [];

// for(var i=0; i< arr.length; i++){ // 实际使用的是这个
for(var i=0; i< arr.length+1; i++){ // 注意,是length+1,比数组的长度大
var tem = iter.next(); // 每次迭代时更新next
console.log(tem.done); // 这里可以看到更新后的done都是false
if(tem.done !== true){ // 遍历迭代器结束done才是true
console.log(tem.value);
a[i]=tem.value;
}
}
console.log(a);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #二位数组排序
function sortArr(arr) {
var goNext = true;
var entries = arr.entries();
while (goNext) {
var result = entries.next();
if (result.done !== true) {
result.value[1].sort((a, b) => a - b);
goNext = true;
} else {
goNext = false;
}
}
return arr;
}

var arr = [[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]];
sortArr(arr);

forEach

callback is not invoked for index properties that have been deleted or are uninitialized

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 # arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

const arraySparse = [1,3,,7]
let numCallbackRuns = 0

arraySparse.forEach((element) => {
console.log(element)
numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7

let words = ['one', 'two', 'three', 'four']
words.forEach((word) => {
console.log(word)
if (word === 'two') {
words.shift()
}
})
// one
// two
// four

values

values ,迭代value
keys, 迭代index

1
2
3
4
5
6
7
8
9
10
11
12
13
 # arr.values()

const array1 = ['a', 'b', 'c'];
const iterator = array1.values();

for (const value of iterator) {
console.log(value);
}

// expected output: "a"
// expected output: "b"
// expected output: "c"

flat

抽取子元素,按原来顺序,组合后返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 # var newArray = arr.flat([depth]);,default 1

var arr1 = [1, 2, [3, 4]];
arr1.flat(); // 默认1
// [1, 2, 3, 4]


var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

# 剔除空元素
const arr5 = [1, 2, , 4, 5];
arr5.flat();
// [1, 2, 4, 5]

map+flat

1
2
3
4
5
6
7
8
9
10
11
# var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// return element for new_array
}[, thisArg])

let arr1 = ["it's Sunny in", "", "California"];

arr1.map(x => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in", "", "California"]

reduce

initialValue 是推荐提供的
If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

1
2
3
4
5
6
7
8
9
10
11
12
# arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

let maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
[ ].reduce( maxCallback ); // TypeError

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue
}) // 10

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue
},10) // 20

reduceRight

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
(accumulator, currentValue) => {
console.log(accumulator);
return accumulator.concat(currentValue)
},['a']
);

console.log(array1);


> Array ["a"]
> Array ["a", 4, 5]
> Array ["a", 4, 5, 2, 3]
> Array ["a", 4, 5, 2, 3, 0, 1]

fill

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 # arr.fill(value[, start[, end]]) 

const array1 = [1, 2, 3, 4];

// 从下标2开始,到4结束,用0替换, 不包括终止索引
console.log(array1.fill(0, 2, 4));
console.log(array1); // 修改自身,而非copy

// [1, 2, 0, 0]
// [1, 2, 0, 0]

//special
const ss = [].fill.call({ length: 3 }, 4)
console.log(ss);

// {0: 4, 1: 4, 2: 4, length: 3}

// A single object, referenced by each slot of the array:
let arr = Array(3).fill({}) // [{}, {}, {}]
arr[0].hi = "hi" // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

splice

替换或者添加元素,影响原数组

1
2
3
4
5
6
7
8
9
10
11
12
13
# let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May'); # 长度不足,进行扩充
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

copyWithin

copy + part Change,不影响原来的

1
2
3
4
5
6
7
8
9
10
11
# arr.copyWithin(target[, start[, end]])

const array1 = ['a', 'b', 'c', 'd', 'e'];
// copy to index 1 all elements from index 3 to the end
console.log(array1);
console.log(array1.copyWithin(1, 3));

//output
["a", "b", "c", "d", "e"]
["a", "d", "e", "d", "e"]

shift

删除数组第一个元素,修改原数组
pop 删除的是数组,最后一个元素,也修改原数组

1
2
3
4
5
6
7
8
9
10
11
12
# arr.shift()

const array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// expected output: Array [2, 3]

console.log(firstElement);
// expected output: 1

unshift

开始位置添加元素

1
2
3
4
5
6
7
8
9
10
11
# arr.unshift(element1[, ...[, elementN]])

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// expected output: 5

console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]


Date

1
Date.now()

2.时间字符串解析

1
2
3
4
5
6
7
8
9
10
# 推荐,还是手动解析,
const unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
const javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

3.时区偏差

1
2
3
# 如果本地时区先于协调世界时,则该差值为正值,如果后于协调世界时则为负值
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

Set

1.从[]得到集合set

1
2
# 常用于数组出重
const set1 = new Set([1, 2, 3, 4, 5]);

2.判断是否包含某一项-has

1
2
 console.log(set1.has(5));
// expected output: true

3.entries

1
2
3
4
5
6
7
8
9
var mySet = new Set();
mySet.add("foobar");
mySet.add(1);
mySet.add("baz");

var setIter = mySet.entries();
console.log(setIter.next().value); // ["foobar", "foobar"]
console.log(setIter.next().value); // [1, 1]
console.log(setIter.next().value); // ["baz", "baz"]

4. values

1
2
3
4
5
6
7
8
9
10
var mySet = new Set();
mySet.add("foo");
mySet.add("bar");
mySet.add("baz");

var setIter = mySet.values();

console.log(setIter.next().value); // "foo"
console.log(setIter.next().value); // "bar"
console.log(setIter.next().value); // "baz"

String

1.统计字符- charCodeAt

1
2
3
4
5
6
7
var count = 0;
var str = "23ab2232322 k23ji2";
for(var i = 0 ;i < str.length; i++){
if(str.charCodeAt(i) === 69){
count++;
}
}

2.校验是否存在匹配-match

1
2
3
4
5
6
# 未找到匹配则为null
var str = 'For more information, see Chapter 3.4.5.1';
var re = /see (chapter \d+(\.\d)*)/i;
var found = str.match(re);

console.log(found);

3.子字符搜索

1
2
3
4
5
var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be')); // true
console.log(str.includes('question')); // true
console.log(str.includes('nonexistent')); // false

4. 返回所有匹配-matchAll

1
2
3
4
let regexp = /t(e)(st(\d?))/g;
let str = 'test1test2';

let array = [...str.matchAll(regexp)];

5. 截取子字符串,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 # 不影响原有的
const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// expected output: "the lazy dog."

console.log(str.slice(-9, -5));
// expected output: "lazy"

# substr 将废弃

# substring
var anyString = "Mozilla";

// 输出 "Moz"
console.log(anyString.substring(0,3));

6.删除字符串两边空白- trim

1
2
3
4
5
6
7
const greeting = '   Hello world!   ';

console.log(greeting);
// expected output: " Hello world! ";

console.log(greeting.trim());
// expected output: "Hello world!";

proxy

定制返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 let products = new Proxy({
browsers: ['Internet Explorer', 'Netscape']
}, {
get: function(obj, prop) {
// 附加一个属性
if (prop === 'latestBrowser') {
return obj.browsers[obj.browsers.length - 1];
}

// 默认行为是返回属性值
return obj[prop];
},
set: function(obj, prop, value) {
// 附加属性
if (prop === 'latestBrowser') {
obj.browsers.push(value);
return;
}

// 如果不是数组,则进行转换
if (typeof value === 'string') {
value = [value];
}

// 默认行为是保存属性值
obj[prop] = value;

// 表示成功
return true;
}
});

console.log(products.browsers); // ['Internet Explorer', 'Netscape']
products.browsers = 'Firefox'; // 如果不小心传入了一个字符串
console.log(products.browsers); // ['Firefox'] <- 也没问题, 得到的依旧是一个数组

products.latestBrowser = 'Chrome';
console.log(products.browsers); // ['Firefox', 'Chrome']
console.log(products.latestBrowser); // 'Chrome'

类型安全

||

1
a = a || b 

??

1
2
3
4
5
6
7
8
9
10
const a = undefined;
const b = 22;
const c = a ?? b;
const d = a || b;
console.log(c);
console.log(d);

//output
22
22

更多推荐

Angular开发利器

Angular8深入了解Directive指令

Angular8 HttpClient 30分钟深入了解下

参考

array

????](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table)

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏